package com.hlju.reggie.common;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

//拦截指定类型的控制器
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//将当前类中方法的返回值R对象转为json在返回
@ResponseBody
public class GloabExceptionHandler {

    //具体处理某个异常的方法
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //获取异常信息
        String message = ex.getMessage();
        System.out.println("拦截到了异常====>"+message);
        //判断当前异常信息是否包含指定内容
        if(message.contains("Duplicate entry")){
            //对异常信息字符串切割 根据空格切割
            String[] split = message.split(" ");
            //获取数组中参数的信息拼接成返回的错误信息
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    //自定义异常信息处理
    @ExceptionHandler(CustException.class)
    public R<String> custException(CustException e){
        System.out.println("拦截到了自定义异常====>"+e.getMessage());
        return R.error(e.getMessage());
    }


}
